/**
 * Created by caspar on 16-9-1.
 */
// 判断浏览器UA
var mobile = {
    getPlatform: function getPlatform() {
        var platform;
        if (mobile.b().android) {
            platform = 'android';
        } else if (mobile.b().ios || mobile.b().iPhone) {
            platform = 'ios';
        } else {
            platform = 'other';
            /*if (location.origin == 'http://test.aos.antfre.com:8858') {
             platform = other;
             } else {
             location.href = 'http://www.antfre.com/';
             }*/
        }
        return platform;
    },
    b: function browser() {
        var u = navigator.userAgent.toLowerCase();
        var app = navigator.appVersion.toLowerCase();
        return {
            txt: u, // 浏览器版本信息
            version: (u.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], // 版本号
            msie: /msie/.test(u) && !/opera/.test(u), // IE内核
            mozilla: /mozilla/.test(u) && !/(compatible|webkit)/.test(u), // 火狐浏览器
            safari: /safari/.test(u) && !/chrome/.test(u), //是否为safair
            chrome: /chrome/.test(u), //是否为chrome
            opera: /opera/.test(u), //是否为oprea
            presto: u.indexOf('presto/') > -1, //opera内核
            webKit: u.indexOf('applewebkit/') > -1, //苹果、谷歌内核
            gecko: u.indexOf('gecko/') > -1 && u.indexOf('khtml') == -1, //火狐内核
            mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/), //ios终端
            android: u.indexOf('android') > -1, //android终端
            iPhone: u.indexOf('iphone') > -1, //是否为iPhone
            iPad: u.indexOf('ipad') > -1, //是否iPad
            weixin: u.match(/MicroMessenger/i) == "micromessenger", //是否是微信内置
            webApp: !!u.match(/applewebkit.*mobile.*/) && u.indexOf('safari/') == -1 //是否web应该程序，没有头部与底部
        };
    }

};
var shareId //分享链接
var param = $.urlGet(),
    order_no = param.order_no
var params = JSON.parse(window.localStorage.user);
var redirect = JSON.parse(decodeURIComponent(params['redirect']));
$(function () {
    // console.log(window.location)
    // console.log(order_no)
    // console.log(param.order_no)
    sessionStorage.removeItem('cart')
    _hmt.push(['_trackEvent', "订单", "订单支付成功"]);
    getShowView(order_no)
    console.log(params.platform)
    var alipay = window.sessionStorage.alipay
    // params.platform = 'alipay'
    if (params.platform === 'alipay'){
        if(!alipay){
            window.sessionStorage.alipay = '1'
            behavior.track("成功支付",{
                'payType':'alipay',
                'orderId':order_no
            })
        }
    }
});
function getShowView() {
    $.ajax({
        url: configApi('/order/view'),
        data: {
            no:order_no,
            access_token:redirect.token,
            platform:params.platform
        },
        dataType: 'json',
        type: "get",
    }).done(function (res) {
        if (res.success){
            console.log(res)
            // shareId = res.data.share.id
            console.log(shareId)
            foodView(res.data,order_no)
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    }).fail(function () {
        "use strict"
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    })
}

function foodView(foods,order_no) {
    "use strict"
    console.log(foods)
    var html = ''
    $.each(foods.orderItem,function (index,item) {
            html +='<div class="food-content">'
            html +='<div class="food">'
            html +='<div class="name"><img src="'+ item.item.img +'" alt="">'+ item.name +'</div>'
            html +='<div class="count"><span class="num">x&nbsp<span>'+ item.num +'</span></span><span class="food-price">¥<span class="price">'+ item.price +'</span></span></div>'
            html +='</div>'
            html +='</div>'
        })
    $('.gods-list').html(html)
    if (foods.coupon_price == 0){
        $('.discounts').hide()
    }else {
        $('.discounts—price .price').text(foods.coupon_price)
    }
    if (foods.discount_amount == 0){
        $('.discount').hide()
    }else {
        $('.discount—price .price').text(foods.discount_amount)
    }
    $('.price-container .num').text(foods.htotal)
    $('.share_content img').attr('src',foods.shareActivityImgUrl)
    //分享
    if(foods.shareActivityImgUrl){
        if (foods.shareButton == '1'){//分享
            // console.log(params.platform)
            if(params.platform == 'dingTalk'){
                $('.share-container').hide()
                $('.share_content').hide()
                $('.share_icon').hide()
            }else {
                $('.share-container').show()
                $('.share_content').show()
                $('.share_icon').show()
            }
            $.ajax({
                url: configApi('/coupon/share-coupon'),
                data: {
                    no:order_no,
                    access_token:redirect.token
                },
                dataType: 'json',
                type: "post",
                async: false,
            }).done(function (res) {
                if (res.success){
                    shareId = res.data.link
                }else {
                    layer.open({
                        content: res.message
                        ,skin: 'msg'
                        ,time: 2 //2秒后自动关闭
                    });
                }
            }).fail(function () {
                layer.open({
                    content: "服务器异常,请退出重试"
                    ,skin: 'msg'
                    ,time: 2 //2秒后自动关闭
                });
            })
            if(params.platform == 'wechat'){//活动弹窗
                //微信
                wechat()
                $('.share—submit').click(function () {
                    "use strict"
                    $('.share_content').hide()
                    $('.here-conent').show()
                })
                $('.share_icon').click(function () {
                    "use strict"
                    // wechat()
                    $('.share-container').show()
                    $('.share_content').hide()
                    $('.here-conent').show()

                })

            }else {
                ready(function () {
                    aliShare()
                    document.querySelector('.share—submit').addEventListener('click', function () {
                        Alipay()
                    })
                    document.querySelector('.share_icon').addEventListener('click', function () {
                        Alipay()
                    })
                })
            }
        }else if(foods.shareButton == '2'){
            $('.share-container').show()
            $('.share—submit').click(function () {
                // if (params.platform === "wechat"){
                //     _hmt.push(['_trackEvent', "广告", "in同城趴"]);
                // }else {
                _hmt.push(['_trackEvent', "广告", "旅人星球"]);
                // }
                setTimeout(function () {
                    window.location.href = foods.shareActivityUrl
                },200)
            })
            // window.location.href = foods.shareActivityUrl
        } else {
            $('.share_icon').hide()
            $('.share-container').hide()
        }
    }
}
//分享
$('.share_close').click(function () {
    $('.share-container').hide()
})
$('.submit').click(function () {
    window.location.href = '../index.html'
})
function wechat() {
    var params = JSON.parse(window.localStorage.user);
    console.log()
    var token = JSON.parse(decodeURIComponent(params['redirect'])).token;
    $.ajax({
        url: configApi('/coupon/share-text'),
        data: {
            access_token:token
        },
        dataType: 'json',
        type: "get",
    }).done(function (res) {
        console.log(res)
        if (res.success){
            console.log(res.data)
            var data = res.data
            var title = data.title,
                desc = data.desc,
                img = data.icon,
                link = window.location.origin + '/webApp/shareParams.html?lineLink='+ shareId +''
            console.log(link)
            console.log(shareId)
            wxShare(title,desc,img,link,token,shareId.split('share_id=')[1])
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    }).fail(function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    })
    // $('.share_content').hide()
    // $('.here-conent').show()
}
function ready(callback) {
    // 如果jsbridge已经注入则直接调用
    if (window.AlipayJSBridge) {
        callback && callback();
    } else {
        // 如果没有注入则监听注入的事件
        document.addEventListener('AlipayJSBridgeReady', callback, false);
    }
}
function Alipay() {
    var params = JSON.parse(window.localStorage.user);
    var token = JSON.parse(decodeURIComponent(params['redirect'])).token;
    $.ajax({
        url: configApi('/coupon/share-text'),
        data: {
            access_token:token
        },
        dataType: 'json',
        type: "get",
    }).done(function (res) {
        console.log(res)
        if (res.success){
            console.log(res.data)
            var data = res.data
            var title = data.title,
                desc = data.desc,
                img = data.icon,
                link = window.location.origin + '/webApp/shareParams.html?lineLink='+ shareId +''
            // console.log(link)
            // console.log(shareId)
            $('.share-container').hide()
            AlipayJSBridge.call("startShare", {
                'onlySelectChannel': [
                    "Weibo",
                    "ALPContact",
                    "ALPTimeLine",
                    "SMS",
                    "Weixin",
                    "WeixinTimeLine",
                    "QQ",
                    "QQZone",
                    "OpenInSafari",
                ]
            },function (data) {
                AlipayJSBridge.call("shareToChannel", {
                    name: data.channelName,
                    param: {
                        title: title,
                        content: desc,
                        imageUrl: img,
                        captureScreen: false, //是否分享当前页面的截图
                        url: link,
                    }
                },function (result) {
                    // layer.open({
                    //     content:'分享成功'
                    //     ,skin: 'msg'
                    //     ,time: 2 //2秒后自动关闭
                    // });
                    shareHaer(token,shareId.split('share_id=')[1])
                })
            })
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    }).fail(function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    })
}


